import { init } from 'snabbdom/src/package/init'
import { h } from 'snabbdom/src/package/h'
import { eventListenersModule } from 'snabbdom/src/package/modules/eventlisteners'
import { classModule } from 'snabbdom/src/package/modules/class'

const patch = init([classModule, eventListenersModule])

let oldVnode

let initData = [
  {id: 5, text: '火影忍者'},
  {id: 2, text: '海贼王'},
  {id: 4, text: '死神'},
  {id: 1, text: '一拳超人'},
  {id: 0, text: '钢之炼金术师'},
  {id: 9, text: '叛逆的鲁鲁修'}
]

const Animes = ['进击的巨人', '灵能百分百', '犬夜叉']

function handleAdd(data) {
  const ids = data.map(v => v.id)
  const lastId = ids.length ? Math.max(...ids) : 0
  const params = [
    {id: lastId+1, text: Animes[Math.floor(Math.random()*3)]},
    ...data,
  ]
  oldVnode = patch(oldVnode, createVnode(params))
}

function sortBy(flag, data) {
  const params = data.sort((a, b) => flag === 'id' ? a[flag] - b[flag] : a[flag].localeCompare(b[flag]))
  oldVnode = patch(oldVnode, createVnode(params))
}

function delBy(id, data) {
  const params = data.filter(v => v.id !== id)
  oldVnode = patch(oldVnode, createVnode(params))
}

function createVnode(data = []) {
  return h(
    'div.container',
    [
      h('h3', {}, 'Hello Snabbdom'),
      h('div.option', [
        h('div.left', [
          h('span', {}, '排序字段：'),
          h('span.btn', {on: {click: () => sortBy('id', data)}}, '序号'),
          h('span.btn', {on: {click: () => sortBy('text', data)}}, '内容')
        ]),
        h('span.btn', {on: {click: () => handleAdd(data)}}, '添加')
      ]),
      h('ul', data.map(v => h('li.del', {key: v.id, on: {click: () => delBy(v.id, data)}}, `${v.id} -- ${v.text}`)))
    ]
  )
} 

oldVnode = patch(
  document.querySelector('#app'),
  createVnode(initData)
)